var attendanceType;
var id;
var groupid;
var iconid;
var subid;
var menuid;
var index;
var taskDetailsListTijaio;
var taskDetailsListTijaio_tow=[];
var taskDetailsList;
var points2 = [];
var points3 = [];
var idArray = [];
var listEquipmentIdArray=[];
var demoArray = [{
		id: "97eabce721e1453895e6dadf68348bd3",
		lat: "29.53473832194754",
		lng: "106.52611584943034"
	},
	{
		id: "1fd20ea930bd4b15aa8ec76cf8fd6763",
		lat: "29.53732357442451",
		lng: "106.52156725598478"
	},
	{
		id: "2b056c3904fe463eb69991ecb13fed13",
		lat: "29.538133029082378",
		lng: "106.51767037925812"
	}
]
//var bm = new BMap.Map("allmap2");
var map2 = new AMap.Map('allmap2');
$(function () {
	groupid = ly.getUrlParam("groupid");
	iconid = ly.getUrlParam("iconid");
	subid = ly.getUrlParam("subid");
	menuid = ly.getUrlParam("menuid");

	attendanceType = ly.getUrlParam("attendanceType");
	id = ly.getUrlParam("id");
	if (attendanceType == 2) {
		$(".body_title").text("查询");
		$(".allmap_creat").hide();
		$(".form").getForm({
			'ajaxform': true,
			id: id
		}, function (data) {
			$("#save-btn-commodityClassification").hide();
			if (data.taskDetailsList != null && data.taskDetailsList != '') {
				taskDetailsList = data.taskDetailsList;
				writeTaskDetailsList(taskDetailsList);
			}
		});
		$(".addDetailsList").remove();
		$(".radio").attr("disabled", "disabled");
	} else {
		$(".allmap_creat").hide();
		$(".taskLine").hide();

	}

	//提交
	$("body").on("click", "#save-btn-commodityClassification", function (event) {
		event.preventDefault();
		var success = $('.form').validate('submitValidate');
		if (success) {
			//验证通过提交表单
			submitFom();
		}
	})

	//确认任务线路
	$("body").on("click", "#submit-btn-audit", function () {
		var DatanewArray=[];
		taskDetailsListTijaio = new Array();
		var obj = {};
		console.log("---------------确认任务线路点击事件---------------");
		if ($(".id").length < 2) {
			ly.toast('请至少选择两条线路');
			return false
		} else {
			$(".id").each(function (i, v) {
				var id = $(this).val();
				obj = {
					'equipmentId': id,
					'taskOperation': $("#taskOperation" + id).find("option:selected").val(),
					'taskFlow': $(".taskFlow" + id).html(),
					'detailsExplain': $("#detailsExplain" + id).val()
				}
				taskDetailsListTijaio.push(obj);

			});
			console.log(points2,taskDetailsListTijaio,111)
			for (let i = 0; i < points2.length; i++) {
				var detailsExplain = taskDetailsListTijaio.find(function (item) {
					return item.equipmentId == points2[i].id
				}).detailsExplain;
				console.log("detailsExplain="+detailsExplain);
				taskDetailsListTijaio_tow.push({
					'equipmentId': points2[i].id,
					'taskOperation':1,
					'taskFlow': i+1,
					'detailsExplain':detailsExplain
				})
				
			}
			// debugger
			$(".allmap_creat").show()
			allmap_creat(points2);
			layer.close(index);
		}
	});
	$("body").on("click", "#addDetailsList", function () {
		creatDetailsList(points2);
		//creatDetailsList(taskDetailsList);
	});
	function allmap_creat(demoArray) {
		var markers;
		var allmap_creat = new AMap.Map('allmap_creat');
		var points = [];
		for (let i = 0; i < demoArray.length; i++) {
			points.push({
				lng: demoArray[i].lng,
				lat: demoArray[i].lat,
				data: 1
			})

		}
		for (var i = 0; i < points.length; i++) {
			var jfong = [points[i].lng, points[i].lat];
			markers = new AMap.Marker({
				resizeEnable: true, //是否监控地图容器尺寸变化
				zoom: 6, //初始地图级别
				position: jfong,
				zIndex: 101,
				map: allmap_creat,
			});

			var markerContent = document.createElement("div");
			markerContent.className = "markerBOX";
			var markerImg = document.createElement("img");
			markerImg.className = "markerlnglat";
			markerImg.src = "../../img/mark_bs.png"
			markerContent.appendChild(markerImg);
			var markerNum = document.createElement("span");
			markerNum.className = 'marker-number';
			markerNum.innerHTML = i + 1;
			markerContent.appendChild(markerNum);
			markers.setContent(markerContent); //更新点标记内容
		}
		allmap_creat.setZoom(10, 8)
		allmap_creat.add(markers); //添加到地图
	}

});

/*
 * 提交表单
 */
function submitFom() {
	if (taskDetailsListTijaio == null || taskDetailsListTijaio.length == 0) {
		ly.toast("请选择任务执行路线");
		return false;
	}
	var taskLineName = $("#taskLineName").val();
	var DatanewArray=taskDetailsListTijaio_tow.reduce(function(prev,element){
	  if(!prev.find(el=>el.equipmentId==element.equipmentId)) {
		prev.push(element)
	  }
	  return prev
	},[])
	if (attendanceType == 1) {
		//新增
		obj = {
			'lineName': taskLineName,
			'taskDetailsList': DatanewArray
		};
	} else {
		//修改
		var thisId = $("#id").val();
		obj = {
			'lineName': taskLineName,
			'taskDetailsList': taskDetailsListTijaio,
			'id': thisId
		};
	}
	var url = site.gateUrl + "/back/taskLine/insertOrUpdateTaskLine";
	request({
		url: url,
		data: obj,
		type: "post",
		callback: function (f) {
			
			if (f.code == "rest.success") {
				if (attendanceType == 1) {
					ly.alert('保存成功', function () {
						ly.goto("taskLine-list.html");
					});
				} else {
					ly.alert('修改成功', function () {
						ly.goto("taskLine-list.html");
					});
				}
			} else {
				ly.toast(f.desc);
			}
		}
	});

}

//打开弹窗
function creatDetailsList(taskDetailsList) {
	$("#equipmentType").getSelect({
		type: "select",
		asName: "equipmentType",
		code: "equipmentType",
		default: ''
	});
	selectEquipmentListBack('', '', taskDetailsList);
	index = layer.open({
		title: false,
		type: 1,
		area: ['93%', '600px'], //设置宽度,高度自适应
		closeBtn: 0,
		content: $(".create_merchant"),
		success: function (layero, index) {
			$("#layui-layer" + index).find(".goback,.icon-close").on("click", function () {
				if(points2.length == 0){
					$(".allmap_creat").hide()
				}
				document.getElementById("formMerchant").reset();
				$("#layui-layer" + index).find(".valid").remove();
				$("#layui-layer" + index).find("div").removeClass('error success');
				layer.close(index);
			});
		}
	});
}



//选择上级部门
function selectTeamList(businessId) {
	var list = new Array();
	request({
		url: site.gateUrl + "/back/team/selectTeamList",
		data: {
			'num': 1,
			'size': 100,
			'isUsing': 1
		},
		type: "get",
		ajaxform: true,
		callback: function (f) {
		
			if (f.code == "rest.success") {
				/*var obj = {value:' ',display:'请选择'};
				list.push(obj);*/
				var obj = {};
				if (f.result.list != null && f.result.list != '') {
					obj = {};
					$.each(f.result.list, function (i, o) {
						obj = {
							value: o.id,
							display: o.teamName
						};
						list.push(obj);
					});
				}
				$("#teamId").getSelect({
					type: "checkbox",
					asName: "teamId",
					list: list,
					default: businessId
				});
			}
		}
	});
}

//选择设备
function selectEquipmentListBack(equipmentType, equipmentName, taskDetailsList) {
	var changeThisList = "";
	var listEquipmentId = '';
	//$("#changeThisList").empty();

	if (taskDetailsList != null && taskDetailsList != '') {
		for (let i = 0; i < taskDetailsList.length; i++) {
			listEquipmentId = taskDetailsList[i].id;
			var selected='';
			if(listEquipmentIdArray.length){
				selected = listEquipmentIdArray.toString();
			}
			if(selected.indexOf(id)<0 &&listEquipmentId){
				 listEquipmentIdArray.push(listEquipmentId); 
			}
		}
	}
	request({
		url: site.gateUrl + "/back/attendanceBack/selectEquipmentListBack",
		data: {
			'num': 1,
			'size': 100,
			'isUsing': 1,
			'equipmentType': equipmentType,
			'equipmentName': equipmentName
		},
		type: "get",
		"ajaxform": true,
		callback: function (f) {
				
			if (f.code == "rest.success") {
				var equipmentList = null;
				var Oid=[];
				if (f.result.list != null && f.result.list != '') {
					obj = {};
			
					$.each(f.result.list, function (i, o) {
						var selected='';
						if(listEquipmentIdArray.length){
							selected = listEquipmentIdArray.toString();
						}
						equipmentList += "<tr>"
						equipmentList += "<td>" + o.equipmentName + "</td>"
						equipmentList += "<td>" + o.equipmentTypeDisplay + "</td>"
						equipmentList += "<td>" + o.lat + "</td>"
						equipmentList += "<td>" + o.log + "</td>"
						equipmentList += "<td>" + o.equipmentAddress + "</td>"
						equipmentList += "<td class='equipment" + o.id + "' onclick=\"changeThisEquipment('" + o.id + "','" + o.equipmentName + "','" + o.lat + "','" + o.log + "','"+i+"')\">"
				
						if(selected&&o.id&&selected.indexOf(o.id)>-1){
							equipmentList += "<span class='equipmentBtn'>已选择</span>"	
						}else{
							equipmentList += "<span class='equipmentBtn'>选择</span>"
						}
						equipmentList += "</td>"
						equipmentList += "</tr>"
					});
					$("#equipmentList").html(equipmentList);
					if(taskDetailsList){
						$.each(taskDetailsList, function (i, o) {
							changeThisList += "<tr class='deleteThisEquipment" + o.id + "'>"
							changeThisList += '<input class="id" type="hidden" value="">'
							changeThisList += '<td class="taskFlow paixu">'+(i-0+1)+'</td>'
							changeThisList += '<td>'+o.equipmentName+'</td>'
							// changeThisList += '<td>'
							// changeThisList += '<select id="taskOperation" class="">'
							// changeThisList += '<option value="1">签</option>'
							// changeThisList += '<option value="2">报</option>'
							// changeThisList += '</select>'
							// changeThisList += '</td>'
							changeThisList += '<td>'
							changeThisList += '<input type="text" maxlength="100" placeholder="请输入100字以内的说明" class="ipt" id="detailsExplain">'
							changeThisList += '</td>'
							changeThisList += "<td onclick=\"deleteThisEquipment('" + o.id + "')\">"
							changeThisList += '<span class="equipmentBtn">删除</span>'
							changeThisList += '</td>'
							changeThisList += '</tr>'	
							
					//	changeThisList = "<tr class='deleteThisEquipment" + o.id + "'><input class='id' type='hidden' value='" + o.id + "'><td>" + (i + 1) + "</td><td>" + o.equipmentName + "</td><td onclick=\"deleteThisEquipment('" + o.id + "')\"><span class='equipmentBtn'>删除</span></td></tr>";
					
				});
					$("#changeThisList").html(changeThisList);
					}
				}
				
			}
		}
	});
}
function isArray(obj) {
    return typeof obj == 'object' && obj.constructor == Array
}
/****
 * 
 * @param {Object} id
 * @param {Object} equipmentName
 */
function changeThisEquipment(id, equipmentName, lat, log,inde) {
	//points2.length=0
	
	if ($(".equipment" + id).find('.equipmentBtn').text() == '已选择') {
		
		ly.toast("已选择，不可重复选择");
	
		return false;
	}
	idArray.push(id)

	var length = parseFloat($("#changeThisList tr").length) + 1;
	var changeThisList = "<tr class='deleteThisEquipment" + id + "'><input class='id' type='hidden' value='" + id + "'><td class='taskFlow" + id + " paixu'>" + length + "</td><td>" + equipmentName + "</td>" +
		"<td><input type='text' maxLength='100' placeholder='请输入100字以内的说明' class='ipt' id='detailsExplain" + id + "'></td><td onclick=\"deleteThisEquipment('" + id + "')\"><span class='equipmentBtn'>删除</span></td></tr>";
	$("#changeThisList").append(changeThisList);
	 $(".equipment" + id).html("<span class='equipmentBtn'>已选择</span>");
	selectDictBasicsWithGroup(id);
	var log_list = {
		'id': id,
		'equipmentName':equipmentName,
		'lng': log,
		'lat': lat,
	}
	
	points2.push(log_list);
	
	removeRepeat(points2,points3)

	
	//
	for (var i = 0; i < points2.length; i++) {
		var jfong = [points2[i].lng, points2[i].lat];
		markers = new AMap.Marker({
			resizeEnable: true, //是否监控地图容器尺寸变化
			zoom: 6, //初始地图级别
			position: jfong,
			zIndex: 101,
			map: map2,
		});
		var markerContent = document.createElement("div");
		markerContent.className = "markerBOX";
		var markerImg = document.createElement("img");
		markerImg.className = "markerlnglat";
		markerImg.src = "../../img/mark_bs.png"
		markerContent.appendChild(markerImg);
		var markerNum = document.createElement("span");
		markerNum.className = 'marker-number';
		markerNum.innerHTML = i + 1;
		markerContent.appendChild(markerNum);
		markers.setContent(markerContent); //更新点标记内
	}
	map2.panTo([log, lat]); //根据选择的点调整位置
	map2.setZoom(10, 8)
	map2.add(markers); //添加到地图

}
function removeRepeat(oldArr,allArr){
	for(var i=0;i<oldArr.length;i++){
		　　var flag = true;
		　　for(var j=0;j<allArr.length;j++){
		　　　　if(oldArr[i].id == allArr[j].id){
		　　　　　　flag = false;
		　　　　};
		　　}; 
		　　if(flag){
		　　　　allArr.push(oldArr[i]);
		　　};
		};
		
}
  function StrArray(str){
	var newStr="";
	for(var i=0;i<str.length;i++){
	if(newStr.indexOf(str[i])==-1){
	newStr+=str[i];
	}
	}
	return newStr;
	}
	// Array.prototype.removes=function(value){
		
	// 	var index=this.indeOf(value);
	// 	if(index>-1){
	// 		this.splice(index,1);
	// 	}
	// }
function deleteThisEquipment(id) {
	var markersArr = [];
	map2.clearMap();
	$(".deleteThisEquipment" + id).remove();
	$(".equipment" + id).html("<span class='equipmentBtn'>选择</span>")
	$(".paixu").each(function (i, o) {
		$(o).html(i + 1);
	});

			for (let i = 0; i < points2.length; i++) {
				
					if(points2[i].id == id){
					
						points2.splice(i,1);
					}	 
			}
			for (let i = 0; i < points3.length; i++) {
					
					if(points3[i].id == id){
					
						points3.splice(i,1);
					}	 
			}
			for (let i = 0; i < listEquipmentIdArray.length; i++) {
					
				if(listEquipmentIdArray[i] == id){
				
					listEquipmentIdArray.splice(i,1);
				}	 
			}

	for (let i = 0, markerBox; i < points2.length; i++) {
		if (points2[i].id != id) {
			markerBox = new AMap.Marker({
				map: map2,
				position: [points2[i].lng, points2[i].lat],
			});
			var markerContent = document.createElement("div");
			markerContent.className = "markerBOX";
			var markerImg = document.createElement("img");
			markerImg.className = "markerlnglat";
			markerImg.src = "../../img/mark_bs.png"
			markerContent.appendChild(markerImg);
			var markerNum = document.createElement("span");
			markerNum.className = 'marker-number';
			markerNum.innerHTML = i + 1;
			markerContent.appendChild(markerNum);
			markerBox.setContent(markerContent); //更新点标记内
			markersArr.push(markerBox);
		} else {
			points2.splice(i, 1);
			idArray.splice(i, 1);
		}
	}
	map2.setZoom(10, 8)
}

//选择工种
function selectWorkerList(businessId) {
	var list = new Array();
	request({
		url: site.gateUrl + "/back/worker/selectWorkerList",
		data: {
			'num': 1,
			'size': 100,
			'isUsing': 1
		},
		type: "get",
		ajaxform: true,
		callback: function (f) {
		
			if (f.code == "rest.success") {
				var obj = {};
				if (f.result.list != null && f.result.list != '') {
					obj = {};
					$.each(f.result.list, function (i, o) {
						obj = {
							value: o.id,
							display: o.workerName
						};
						list.push(obj);
					});
				}
				$("#workerId").getSelect({
					type: "checkbox",
					asName: "workerId",
					list: list,
					default: businessId
				});
			}
		}
	});
}

//选择用户
function selectUsersList(businessId) {
	var list = new Array();

	var teamId = "";
	var userType = "";
	var assumeOffice = "";
	var backstage_access_personnelstyle = window.localStorage.getItem("backstage-access-personnelstyle");
	if (backstage_access_personnelstyle == 1) {
		assumeOffice = "1";
	} else {
		assumeOffice = "2";
		if(window.localStorage.getItem("backstage-access-teamId") == 'undefined'){
			teamId = '';
		}else{
			teamId = window.localStorage.getItem("backstage-access-teamId");
		}
		userType = window.localStorage.getItem("backstage_access_personnelstyle");
	}
	request({
		url: site.gateUrl + "/sUsers/selectUsersList",
		data: {
			'num': 1,
			'size': 1000,
			'isUsing': 1,
			'userType': userType,
			'teamId': teamId,
			'assumeOffice': assumeOffice
		},
		type: "get",
		"ajaxform": true,
		callback: function (f) {
			
			if (f.code == "rest.success") {
				var obj = {};
				if (f.result.list != null && f.result.list != '') {
					obj = {};
					$.each(f.result.list, function (i, o) {
						obj = {
							value: o.id,
							display: o.nickName
						};
						list.push(obj);
					});
				}
				$("#userId").getSelect({
					type: "checkbox",
					asName: "userId",
					list: list,
					default: businessId
				});
			}
		}
	});

}


//选择字典
function selectDictBasicsWithGroup(id) {
	var list = new Array();
	request({
		url: site.gateUrl + "/dictBasic/selectDictBasicsWithGroup",
		data: {
			'code': 'taskOperation'
		},
		type: "get",
		"ajaxform": true,
		callback: function (f) {
			
			if (f.code == "rest.success") {
				var options = '';
				if (f.result != null && f.result != '') {
					$.each(f.result, function (i, o) {
						options += "<option value='" + o.value + "'>" + o.display + "</option>"
					});
					$("#taskOperation" + id).append(options);
				}
			}
		}
	});
}


/***
 * 选择搜索
 */
function changeSelectTeamList() {

	var equipmentType = $('select[name=equipmentType] option:checked').val();
	var equipmentName = $("#equipmentName").val();
	var taskDetailsList = points2;

	selectEquipmentListBack(equipmentType, equipmentName, taskDetailsList);
}



function writeTaskDetailsList(taskDetailsList) {

	var detailsList = "";
	var points = [
		// new BMap.Point(116.3786889372559, 39.90762965106183),
		// new BMap.Point(116.38632786853032, 39.90795884517671),
		// new BMap.Point(116.39534009082035, 39.907432133833574),
		// new BMap.Point(116.40624058825688, 39.90789300648029),
		// new BMap.Point(116.41413701159672, 39.90795884517671)
	];
	$.each(taskDetailsList, function (i, o) {
		detailsList += "<tr><td>" + o.taskFlow + "</td>" +
			"<td>" + o.taskLat + "</td><td>" + o.taskLog + "</td>" +
			/*"<td>" + o.taskOperationDisplay + "</td>" +*/
			"<td>" + o.detailsExplain + "</td></tr>";
		var sum = {};
		//points.push( new BMap.Point( o.taskLog , o.taskLat))
		sum.lng = o.taskLog;
		sum.lat = o.taskLat;
		sum.data = 1;
		points.push(sum)

	});
	$("#detailsList").append(detailsList);


	//------------------------------------地图START----------------------------------------------
	var markers;
	var map = new AMap.Map('allmap');

	for (var i = 0; i < points.length; i++) {

		var jfong = [points[i].lng, points[i].lat];
		markers = new AMap.Marker({
			resizeEnable: true, //是否监控地图容器尺寸变化
			zoom: 6, //初始地图级别
			position: jfong,
			zIndex: 101,
			map: map,

		});

		var markerContent = document.createElement("div");
		markerContent.className = "markerBOX";
		var markerImg = document.createElement("img");
		markerImg.className = "markerlnglat";
		markerImg.src = "../../img/mark_bs.png"

		markerContent.appendChild(markerImg);


		var markerNum = document.createElement("span");
		markerNum.className = 'marker-number';
		markerNum.innerHTML = i + 1;
		markerContent.appendChild(markerNum);

		markers.setContent(markerContent); //更新点标记内容
	}


	map.setZoom(10, 8)
	map.add(markers); //添加到地图





	//---------------------------------------地图END-------------------------------------------



}